package cn.edu.cdtu.healthclient.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.edu.cdtu.healthclient.domain.Test;
import cn.edu.cdtu.healthclient.domain.TestLog;
import cn.edu.cdtu.healthclient.service.HealthService;
import cn.edu.cdtu.healthclient.service.HealthService.HealthBinder;
import cn.edu.cdtu.healthclient.task.ActivityTaskQueue;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthServerContect;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthTestPargrams;
import cn.edu.scu.healthclient.activity.R;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class TestLogActivity extends Activity {

	/*
	 * 
	 */
	private ActivityTaskQueue taskQueue;
	public ActivityTaskQueue getTaskQueue(){
		return taskQueue;
	}
	/*
	 * 
	 */
	private HealthBinder binder;
	public HealthBinder getBinder(){
		return binder;
	}
	/*
	 * 
	 */
	private ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			binder = null;
			taskQueue.shutdownTaskQueue();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binder = (HealthBinder)service;
			if(!taskQueue.isRunning()){
				taskQueue.start();
			}
		}
	};
	
	/*
	 * 
	 */
	private final Intent serviceIntent = new Intent(HealthService.ACTION);
	
	private ListView listView;
	private TextView topTitle;
	private Test selectTest;
	private TestLog[] testLogs;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		startService(serviceIntent);
    	taskQueue = new ActivityTaskQueue();
//    	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);  
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);
		listView = (ListView) findViewById(R.id.health_test_list);
		topTitle = (TextView) findViewById(R.id.topTitle);  
		Intent intent = getIntent();
		selectTest = (Test) intent.getSerializableExtra(
				HealthTestPargrams.Pargram.SELECT_TEST);
	    topTitle.setText(selectTest.getTest() + " 历史测试记录");
	}
	/* (non-Javadoc)
	 * <p>Title: onStart</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		bindService(serviceIntent, 
        		serviceConnection, Service.BIND_AUTO_CREATE);
		super.onStart();
		taskQueue.addTask(new Thread(new TestLogTaskImplementation()));
	}
	/* (non-Javadoc)
	 * <p>Title: onStop</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		unbindService(serviceConnection);
	}
	/**
	 * 
	 * @ClassName: TestLogTaskImplementation 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class TestLogTaskImplementation implements Runnable{

		/* (non-Javadoc)
		 * <p>Title: run</p> 
		 * <p>Description: </p>  
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			HttpClient httpClient = binder.getHttpClient();
			HttpPost httpPost = new HttpPost(HealthServerContect.SERVER_URL
					+ HealthServerContect.TEST_LOG_SERVLET);
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Option.HEALTH_TEST_OPTION,
					HealthTestPargrams.Option.OptionValue.HEALTH_TEST_OPTION_GET_TEST_LOG));
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Pargram.SELECT_TEST, 
					gson.toJson(selectTest)));
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(postParams,"utf-8"));
				HttpResponse response = httpClient.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String message = EntityUtils.toString(response.getEntity());
					List<TestLog> testLogList = gson.fromJson(message, 
							new TypeToken<List<TestLog>>(){}.getType());
					testLogs = testLogList.toArray(new TestLog[testLogList.size()]);
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							List<Map<String, Object>> listItems = 
									new ArrayList<Map<String,Object>>();
							for (TestLog testLog : testLogs) {
								Map<String, Object> listItem = new HashMap<String, Object>();
								listItem.put("Log_time", testLog.getDate());
								listItems.add(listItem);
							}
							SimpleAdapter simpleAdapter =
									new SimpleAdapter(
											TestLogActivity.this, 
											listItems,
											R.layout.activity_test_adapter_test_log,
											new String[]{"Log_time"}, 
											new int[]{R.id.text_log_time});
							listView.setAdapter(simpleAdapter);
							listView.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {
									// TODO Auto-generated method stub
									Bundle bundle = new Bundle();
									bundle.putSerializable(
											HealthTestPargrams.Pargram.SELECT_TEST
											, selectTest);
									bundle.putSerializable(
											HealthTestPargrams.Pargram.SELECT_TEST_LOG
											, testLogs[position]);
									Intent intent = new Intent(TestLogActivity.this,
											QuestionLogActivity.class);
									intent.putExtras(bundle);
									startActivity(intent);
								}
							});
						}
					});
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
